<template lang="pug">
  div.mn
    div.hd
      top-banner
      split
    div.bd
      div.main-tt
        div.container
          div.tab-w
            div.tab-item(v-for="(item,index) in voteColumnList" :key="item.id" :class="{'active':item.id*1===currentVoteColumn.id*1}")
              div.tab-cell(type="primary" :disabled="!item.isActive" size="medium" @click="handlerClickBtnVoteColumn(item)") {{item.text}}
          <!--div.search-->
          <!--div.search-ipt-->
          <!--el-input(placeholder="请输入内容" suffix-icon="el-icon-search" v-model="searchStr" size="small")-->
          <!--el-button(type="primary" size="small" @click="handlerClickBtnSearch") 搜索-->
          <!--el-button(v-if="searchStr" type="danger" size="small" @click="handlerClickBtnClear") 清除-->
          div.alert-w(v-if="voteColumnList.length")
            el-alert(:title="alertTitle" center type= "error" :closable="false" effect="dark" )
          div.checked-department(v-if="currentVoteColumn.id!==3" :class="{'':btnDisabled,'success':!btnDisabled}")
            div.lab 已选择：
            div.mn
              div.cells
                template(v-for="(item) in voteDepartment")
                  div.cell(:class="{'success':item.length>0}")
                    div.txt-key
                      i.el-icon-success.icon(v-if="item.length>0")
                      i.el-icon-warning.icon(v-else)
                      | {{item.key}}
                    div.txt-len
                      span {{item.length}}
                      | 人
        split
      div.main
        div.container
          div.cells(v-if="voteItemList.length")
            div.cell-w(v-for="(item,index) in voteItemList" :key="item.id" )
              div.cell(@click="handlerClickVoteItem(item)")
                div.avatar-w
                  div.avatar-mn
                    div.avatar(:style="avatarStyle(item)")
                div.text(v-if="currentVoteColumn.id!==3")
                  div.txt-b--1 {{item.department}}
                div.text
                  div.txt-a(v-if="currentVoteColumn.id===1")
                    div.txt-a--1 {{item.courseName}}
                  div.txt-a(v-if="currentVoteColumn.id===2")
                    div.txt-a--1 {{item.name}}
                  div.txt-a(v-if="currentVoteColumn.id===3")
                    div.txt-a--1 {{item.name}}
                div.text(v-if="currentVoteColumn.id===1")
                  div.txt-a
                    div.txt-a--1 {{item.courseType}}
                div.btn-w
                  div.btn(@click.stop="handlerClickVoteItemCheck(item)")
                    span.chk-box(:class="{'active':item.isChecked}")
                      i.el-icon-check
                    | 选择
          div.loading-w(v-else)
            div.loading-msg
              i.el-icon-loading.icon
              span.txt 请稍后……
    div.ft
      split
      div.container.btn-w
        el-button(@click="handlerClickBtnSubmit" type="primary") 提交
</template>

<script type="text/ecmascript-6">
import {voteCourseItemURL, voteTeacherItemURL, voteTeamItemURL, voteSaveURL} from '../config/global.toml'
import VoteTitle from '../components/VoteTitle'
import Split from '../components/Split'
import TopBanner from '../components/TopBanner'
import {mapGetters, mapActions} from 'vuex'
import _ from 'underscore'

export default {
  metaInfo: {
    title: '投票首页'
  },
  data() {
    return {
      searchStr: null,
      voteColumnList: [],
      voteItemList: [],
      courseChecked: {},
      minItemLength: 2,
      maxItemLength: 4,
      explainText: {
        1: `每名学员投选10门课程，科学文化类4门、政治人文类3门、军事基础类3门（各部、系、大队不少于1门课程）`,
        2: `每名学员投选10名教员（各部、系、大队不少于1名教员）`,
        3: '每名学员投选1至4名队干部'
      },
      // 投票部系
      voteDepartment: []
    }
  },
  mounted() {
    // console.log('asdf')
    this.getVoteColumn()
    // 科学文化类
    this.courseType1 = []
    // 政治人文类
    this.courseType2 = []
    // 军事基础类
    this.courseType3 = []
  },
  methods: {
    ...mapActions(['setCurrentVoteColumn']),
    getAvatar(item) {
      let name = this.currentVoteColumn.id === 1 ? item.courseName : item.name
      let researchSection = this.currentVoteColumn.id === 3 ? item.teamBelongs : item.researchSection
      return `/static/avatar/${researchSection}${name}.jpg`
    },
    avatarStyle(item) {
      return {'background-image': `url(${this.getAvatar(item)})`}
    },
    async getVoteColumn() {
      let targetUrls = [
        {
          text: '最受学员欢迎的课程',
          url: voteCourseItemURL,
          maxItemLength: 10,
          minItemLength: 5
        },
        {
          text: '最受学员喜爱的教员',
          url: voteTeacherItemURL,
          maxItemLength: 10,
          minItemLength: 5
        },
        {
          text: '最受学员信服的队干部',
          url: voteTeamItemURL,
          maxItemLength: 5,
          minItemLength: 1
        }
      ]
      let voteColumns = []
      for (let key in targetUrls) {
        let item = targetUrls[key]
        let {data: {data, totalCount}} = await this.$http.get(item.url, {
          params: {
            showType: '0'
          }
        })
        // let voteList = data[0].voteList
        let voteConfig = data[0].voteConfig
        // let isActive = voteList[0].voteCount === null
        // let text = voteConfig.voteName
        let voteColumn = {
          id: voteConfig.id,
          text: item.text,
          totalCount,
          url: item.url,
          maxItemLength: item.maxItemLength,
          minItemLength: item.minItemLength,
          isActive: true
        }
        voteColumns.push(voteColumn)
      }
      this.voteColumnList = voteColumns
      let cVC = voteColumns[0]
      let id = this.$route.params.id
      if (id) {
        cVC = voteColumns.find(e => {
          return e.id === id * 1
        })
      }
      this.handlerClickBtnVoteColumn(cVC)
    },
    handlerClickBtnVoteColumn(item) {
      this.$router.push({name: 'Home', params: {id: item.id}})
      this.setCurrentVoteColumn({
        id: item.id,
        mainTitle: item.text,
        endDate: item.endDate,
        startDate: item.startDate,
        voteType: item.voteType,
        maxItemLength: item.maxItemLength,
        minItemLength: item.minItemLength,
        url: item.url,
        voteList: item.voteList,
        totalCount: item.totalCount
      })
      this.getVoteItems()
    },
    async getVoteItems() {
      this.voteDepartment = []
      let targetUrl = this.currentVoteColumn.url
      // console.log('targetUrl:', targetUrl)
      this.voteItemList = []
      let {data: {data}} = await this.$http.get(targetUrl, {
        params: {
          showType: '1'
        }
      })
      // console.log('totalCount:', totalCount)
      // console.log('voteConfig:', data[0].voteConfig)
      // console.log('data:', data[0].voteList)
      let voteConfig = data[0].voteConfig
      this.currentVoteColumn.endDate = voteConfig.endDate
      this.currentVoteColumn.startDate = voteConfig.startDate
      this.currentVoteColumn.voteType = voteConfig.voteType
      this.minItemLength = this.currentVoteColumn.minItemLength
      this.maxItemLength = this.currentVoteColumn.maxItemLength
      this.oldVoteItems = data[0].voteList
      this.oldVoteDepartmentItems = []
      let tempDepartments = _.indexBy(this.oldVoteItems, 'department')
      for (let key in tempDepartments) {
        this.voteDepartment.push({key, length: 0})
        this.oldVoteDepartmentItems.push(key)
      }
      console.log('this.oldVoteDepartmentItems:', this.oldVoteDepartmentItems)
      let tempVoteItem = data[0].voteList
      if (this.searchStr) {
        tempVoteItem = tempVoteItem.filter(e => {
          return e.name.indexOf(this.searchStr) > -1
        })
        // console.log('1 tempVoteItem', tempVoteItem)
      }
      // console.log('2 tempVoteItem', tempVoteItem)
      this.setVoteDepartment()
      this.voteItemList = tempVoteItem
      this.voteItemList.map(e => {
        this.$set(e, 'isChecked', false)
      })
    },
    /**
     * 设置投票部系
     */
    setVoteDepartment() {
      // let tL2s = []
      // for (let key of this.oldVoteDepartmentItems) {
      //   let tt = this.voteItemsIsChecked.filter(e => {
      //     return e.department === key
      //   })
      //   tL2s.push({key, length: tt ? tt.length : 0})
      // }
    },
    /**
     * 选项点击事件
     * @param item
     */
    handlerClickVoteItem(item) {
      switch (this.currentVoteColumn.id) {
        case 1:
          this.$KalixVoteDetail({
            avatar: this.getAvatar(item),
            title: `${item.department} - ${item.courseName}`,
            html: item.description
          })
          break
        case 2:
          this.$KalixTeacherVoteDetail({
            avatar: this.getAvatar(item),
            model: item
          })
          break
        case 3:
          this.$KalixTeamVoteDetail({
            avatar: this.getAvatar(item),
            model: item
          })
          break
      }
    },
    /**
     * 选项选中事件
     * @param item
     */
    handlerClickVoteItemCheck(item) {
      // console.log('item', item)
      if (!item.isChecked) {
        if (this.voteItemsIsChecked.length < this.maxItemLength) {
          item.isChecked = true
        } else {
          this.showMessage(`最多只能选择 ${this.maxItemLength} 个选项！`)
        }
      } else {
        item.isChecked = !item.isChecked
      }
      // 检查部系
      this.voteDepartment.map(item => {
        let tt = this.voteItemsIsChecked.filter(e => {
          return e.department === item.key
        })
        item.length = tt ? tt.length : 0
      })
      this.checkCourseTypeCount()
      console.log(' ===== this.courseTypeIsPass ===== ', this.courseTypeIsPass())
      console.log(' ===== this.courseType1.length ===== ', this.courseType1.length)
      console.log(' ===== this.courseType2.length ===== ', this.courseType2.length)
      console.log(' ===== this.courseType3.length ===== ', this.courseType3.length)
    },
    /**
     * 搜索按钮点击事件
     * @param item
     */
    handlerClickBtnSearch() {
      this.getVoteItems()
    },
    handlerClickBtnClear() {
      this.searchStr = null
      this.getVoteItems()
    },
    showMessage(message, type = 'error') {
      this.$message({
        message,
        showClose: true,
        type,
        duration: 2000
      })
    },
    // async handlerClickBtnSubmit() {
    // },
    async handlerClickBtnSubmit() {
      let trs = []
      let _msg = !this.btnDisabled ?
        '<div class="vote-result-msg success">您本次投票符合投票规则，投票有效，点击确定按钮，将提交本次投票</div>' :
        '<div class="vote-result-msg warning">您本次投票不符合投票规则，投票无效，请重新投票</div>'
      let voteCnt = 0
      if (this.currentVoteColumn.id !== 3) {
        this.voteDepartment.forEach(e => {
          trs.push(`<tr>
                    <td>${e.key}</td>
                    <td><span>${e.length}</span>票</td>
                  </tr>`)
          voteCnt += e.length
        })
      } else {
        voteCnt = this.voteItemsIsChecked.length
      }
      let tableHtml = ''
      let messageHtml = ''
      let flagSubmit = !this.btnDisabled
      this.checkCourseTypeCount()
      trs.push(`<tr>
                    <td>共计票数</td>
                    <td><span>${voteCnt}</span>票</td>
                  </tr>`)
      tableHtml = `<table class="vote-result-table">${trs.join('')}</table>`
      messageHtml = `<div class="vote-result">
                            ${tableHtml}
                            ${_msg}
                        </div>`
      if (this.currentVoteColumn.id === 1 && voteCnt === 10 && !this.courseTypeIsPass()) {
        flagSubmit = false
        messageHtml = `<div class="vote-result">
                          <div>
                            <div>科学文化类应投 4 票，已投 ${this.courseType1.length} 票</div>
                            <div>政治人文类应投 3 票，已投 ${this.courseType2.length} 票</div>
                            <div>军事基础类应投 3 票，已投 ${this.courseType3.length} 票</div>
                          </div>
                          <div class="vote-result-msg warning">您本次投票不符合投票规则，投票无效，请重新投票</div>
                        </div>`
      }
      console.log(' ===== this.courseTypeIsPass ===== ', this.courseTypeIsPass())
      console.log(' ===== this.courseType1.length ===== ', this.courseType1.length)
      console.log(' ===== this.courseType2.length ===== ', this.courseType2.length)
      console.log(' ===== this.courseType3.length ===== ', this.courseType3.length)
      this.$msgbox({
        title: `${this.currentVoteColumn.mainTitle} - 投票确认`,
        showClose: false,
        message: messageHtml,
        dangerouslyUseHTMLString: true,
        callback: action => {
          if (flagSubmit) {
            this.submitVote()
          }
        }
      })
    },
    async submitVote() {
      if (this.voteItemsIsChecked.length < this.minItemLength) {
        this.showMessage(`至少选择 ${this.minItemLength} 个`)
      } else {
        let result = []
        this.voteItemsIsChecked.forEach(e => {
          result.push(e.id)
        })
        let voteUserId = this.userId
        let startDate = this.currentVoteColumn.startDate
        let endDate = this.currentVoteColumn.endDate
        let voteDate = new Date().getTime()
        let contents = result.join(`,`)
        let voteType = this.currentVoteColumn.voteType
        let voteSubmitData = {voteUserId, startDate, endDate, voteDate, contents, voteType}
        // console.log('voteSubmitData:', voteSubmitData)
        // console.log('this.voteItemsIsChecked:', this.voteItemsIsChecked)
        let tempMsg = null
        // 验证
        switch (this.currentVoteColumn.id) {
          case 1:
            // 各教学单位不少于1门课程
            tempMsg = `各教学单位不少于1门课程`
            break
          case 2:
            // 各教学单位不少于1名教员
            tempMsg = `各教学单位不少于1名教员`
            break
        }
        let tL2s = []
        for (let key of this.oldVoteDepartmentItems) {
          let tt = this.voteItemsIsChecked.filter(e => {
            return e.department === key
          })
          tL2s.push({key, length: tt ? tt.length : 0})
        }
        // console.log('this.oldVoteDepartmentItems:', this.oldVoteDepartmentItems)
        let tL3Index = tL2s.findIndex(e => {
          return e.length === 0
        })
        if (this.currentVoteColumn.id === 3) {
          tL3Index = -1
        }
        console.log('tL2s:', tL2s)
        console.log('tL3Index:', tL3Index)
        let voteItems = tL2s.filter(e => {
          return e.length === 0
        })
        let keys = []
        for (let idx in voteItems) {
          keys.push(voteItems[idx].key)
        }
        console.log('voteItems:', voteItems)
        console.log('keys:', keys.join('，'))
        if (tL3Index > -1) {
          this.showMessage(tempMsg)
        } else {
          let {data: {msg}} = await this.$http.post(voteSaveURL, voteSubmitData)
          this.$alert(msg, '', {
            confirmButtonText: '确定',
            callback: () => {
              this.$router.push({name: 'Thank'})
            }
          })
        }
      }
    },
    /**
     * 检查学科分类
     */
    checkCourseTypeCount() {
      this.courseType1 = []
      this.courseType2 = []
      this.courseType3 = []
      if (this.currentVoteColumn.id === 1) {
        this.voteItemsIsChecked.forEach(item => {
          switch (item.courseType) {
            case '科学文化类':
              this.courseType1.push(item)
              break
            case '政治人文类':
              this.courseType2.push(item)
              break
            case '军事基础类':
              this.courseType3.push(item)
              break
          }
        })
      }
    },
    // 检查学科分类
    courseTypeIsPass() {
      console.log(' ===== this.courseType1.length === 4 ===== ', this.courseType1.length === 4)
      console.log(' ===== this.courseType2.length === 3 ===== ', this.courseType2.length === 3)
      console.log(' ===== this.courseType3.length === 3 ===== ', this.courseType3.length === 3)
      return this.courseType1.length === 4 && this.courseType2.length === 3 && this.courseType3.length === 3
    }
  },
  computed: {
    ...mapGetters(['userId', 'currentVoteColumn']),
    submitType() {
      return this.btnDisabled ? '' : 'primary'
    },
    btnDisabled() {
      let flagA = (this.voteItemsIsChecked.length >= this.minItemLength && this.voteItemsIsChecked.length <= this.maxItemLength)
      let idx = this.voteDepartment.findIndex(item => {
        return item.length === 0
      })
      if (this.currentVoteColumn.id === 3) {
        return !flagA
      } else {
        return !(flagA && idx === -1)
      }
    },
    voteItemsIsChecked() {
      return this.voteItemList.filter(e => {
        return e.isChecked
      })
    },
    alertTitle() {
      return `投票规则：${this.explainText[this.currentVoteColumn.id]}`
    }
  },
  components: {
    VoteTitle,
    Split,
    TopBanner
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "../assets/stylus/VoteHome.styl"
</style>
